//
//  FMDBManager.swift
//  1604_LimitFree
//
//  Created by 杨柳迪 on 16/9/29.
//  Copyright © 2016年 Mabin. All rights reserved.
//

import UIKit

class FMDBManager: NSObject {

    //数据库操作队列
    private var myQueue : FMDatabaseQueue?
    
    //获取单例对象的方法
    class var sharedManager : FMDBManager? {
        
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : FMDBManager? = nil
        }
        
        dispatch_once(&Static.onceToken)
            {
                Static.instance = FMDBManager()
        }
        return Static.instance!
    }
    
    override init() {
       
        //初始化数据库
        //1.文件路径
        let cacher = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
        let  path = cacher?.stringByAppendingString("/collect.db")
        
        //2.创建队列
        myQueue = FMDatabaseQueue(path: path)
        //3.创建表格
        myQueue?.inDatabase({
            (database) in
            let createSql = "create table if not exists collect (collectId integer primary key autoincrement,applicationId varchar(255), name varchar(255), headImage blob)"
            let flag = database.executeUpdate(createSql, withArgumentsInArray: nil)
            if flag != true
            {
                print(database.lastErrorMessage())
            }
        })
    }
    
    //收藏数据,插入数据
    func addCollect(model : CollectModel, finishClosure : (Bool -> Void))
    {
        myQueue?.inDatabase({
            (database) in
            
            let insterSql = "insert into collect (applicationId, name, headImage) values (?,?,?)"
            let data = UIImagePNGRepresentation(model.headImage!)
        })
        
        
    }
}
